/* eslint-disable */
import qs from 'qs'
import { Message } from 'element-ui'
const files = require.context('@/api', false, /^\.\/(?!-).*\.(js)$/)
const filenames = files.keys()

function getModule (filename) {
  const file = files(filename)
  return file.default ? file.default : file
}
const api = {}

filenames.forEach(filename => {
  const name = filename.replace(/^\.\//, '').replace(/\.(js)$/, '')
  if (name === 'app') return false
  api[name] = getModule(filename)
})

export default (ctx, inject) => {
  const { app, $axios, store, redirect } = ctx
  $axios.onRequest(config => {
    const { state: { loggedUser }} = store
    const params = qs.parse(config.data)
    const isJSON = !!params.data //  || config.method === 'delete'
    if (isJSON) {
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
    }
    config.headers.common['Access-Token'] = loggedUser ? loggedUser.access_token : ''
    config.transformRequest = [
      data => {
        data = isJSON ? JSON.stringify(config.method === 'delete' ? data : data.data) : qs.stringify(data)
        return data
      }
    ]
  })

  $axios.onResponse(response => {
    const { data } = response
    const { code, message } = data
    if (code !== '200') {
      if (code === '401') {
        Message.warning('会话已过期，请重新登陆')
        store.commit('setUser', null)
        app.router.replace({ name: 'login' })
      } else {
        Message.warning(message || '服务繁忙')
      }
    }
  })

  $axios.onError(error => {
    if (error.response) {
      const { data } = error.response
      Message.error(data.message)
    } else {
      // Message.error('系统炸了~');
      Message.error('系统错误，请稍后重试~')
    }
  })

  for (const key in api) {
    inject(key, api[key]($axios))
  }
}
